package com.tenqian.media.controller;

import com.alibaba.fastjson.JSONObject;
import com.tenqian.CONSTANT;
import com.tenqian.Result;
import com.tenqian.enums.ResultEnum;
import com.tenqian.utils.HttpClientUtils;
import com.tenqian.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {
    Logger logger = LoggerFactory.getLogger(UploadController.class);

    @RequestMapping("/headImg")
    @ResponseBody
    public JSONObject uploadHeadImg(@RequestParam("headImg") CommonsMultipartFile file, @RequestParam("token") String token, HttpServletRequest req) throws IOException {
        JSONObject result = null;
        try {
            String realPath = req.getSession().getServletContext().getRealPath("/resources/headImg");
            File temp = new File(realPath);
            if (!temp.exists()) {
                temp.mkdirs();
            }
            long startTime = System.currentTimeMillis();
            String fileName = UUID.randomUUID().toString().replaceAll("-", "")
                    + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            File newFile = new File(realPath, fileName);
            //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
            file.transferTo(newFile);
            long endTime = System.currentTimeMillis();
            //调用crm保存头像路径
            result = HttpClientUtils.httpGet(CONSTANT.CRM_URL + "/user/updateHeadImg" +
                    "?headImg=" + "/resources/headImg/" + fileName + "&token=" + token);
        } catch (Exception e) {
            logger.error("上传用户头像失败", e);
            return result;
        }
        return result;
    }

    /**
     * 删除文件
     *
     * @param path 以resource开头的路径
     * @return
     */
    @RequestMapping("/delFile")
    @ResponseBody
    public Result delFile(@RequestParam("path") String path, HttpServletRequest req) {
        try {
            String realPath = req.getSession().getServletContext().getRealPath(path);
            File file = new File(realPath);
            if (file.exists()) {
                file.delete();
            }
            return ResultUtil.success();
        } catch (Exception e) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR);
        }
    }

}
